package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.expimp.CustomExcelReader;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AbstractImpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdTeamExpertact;
import com.ccp.dev.qbdms.model.WQbdTeamExpertgroup;
import com.ccp.dev.qbdms.service.WCustomColumnsService;
import com.ccp.dev.qbdms.service.WQbdTeamExpertactService;
import com.ccp.dev.qbdms.service.WQbdTeamExpertgroupService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 专家活动 信息操作处理控制器
 *
 * @author 王明亮
 * @date 2020-07-03 08:42:32
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "专家活动")
@RequestMapping("/qbdms/wQbdTeamExpertact")
public class WQbdTeamExpertactController extends SysBaseController {
    @Resource
    private WQbdTeamExpertactService wQbdTeamExpertactService;
    @Resource
    private WCustomColumnsService wCustomColumnsService;
    @Resource
    private WQbdTeamExpertgroupService wQbdTeamExpertgroupService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-07-03 08:42:32
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "跳转到专家活动首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        wCustomColumnsService.addCustomCols(request);
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);
        // 当前登录用户id
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        return "wQbdTeamExpertact/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-03 08:42:32
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "附带检索条件的分页查询专家活动", detail = "查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "createtime");
            queryFilter.addFilter("orderSeq", "desc");
        }
        ZhiLiangConst.addQueryFilter(queryFilter);
        //分页数据
        List<WQbdTeamExpertact> pageDatas = wQbdTeamExpertactService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        // 添加编辑按钮权限控制
        ZhiLiangConst.isDataAllowEdit(pageDatas, false);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-07-03 08:42:32
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "跳转到专家活动新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        // 上传附件类型相关
        String fileManagementUploadType = PropertyUtil.getByAlias("fileManagementUploadType", "");
        modelMap.put("fileManagementUploadType", fileManagementUploadType);
        String wjszsdsxlx = PropertyUtil.getByAlias("wjszsdsxlx", "");
        modelMap.put("wjszsdsxlx", wjszsdsxlx);
        return "wQbdTeamExpertact/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wQbdTeamExpertact 保存的对象
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-03 08:42:32
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description = "保存专家活动数据", detail = "<#if isAdd>新增<#else>编辑</#if>专家活动数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdTeamExpertact wQbdTeamExpertact) {
        String id = wQbdTeamExpertact.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd", true);
            //新增操作
            //新增数据前生成随机Id
            wQbdTeamExpertact.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdTeamExpertact);
            //上报状态
            BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();

            if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
                wQbdTeamExpertact.setReportStatus(ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED);
            } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)) {
                wQbdTeamExpertact.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            }
            result = wQbdTeamExpertactService.add(wQbdTeamExpertact);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdTeamExpertact);
            result = wQbdTeamExpertactService.update(wQbdTeamExpertact);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdTeamExpertactService.getOneById(id), wQbdTeamExpertact));
        }
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-07-03 08:42:32
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description = "跳转到专家活动详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        return "wQbdTeamExpertact/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-03 08:42:32
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description = "根据主键id查询专家活动的一条数据", detail = "根据主键id查询专家活动的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdTeamExpertact wQbdTeamExpertact = wQbdTeamExpertactService.getOneById(id);
        if (null == wQbdTeamExpertact) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("get.success", wQbdTeamExpertact);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-03 08:42:32
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "根据主键ID删除专家活动数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdTeamExpertact wQbdTeamExpertact = wQbdTeamExpertactService.getOneById(key);
            if (!userId.equals(wQbdTeamExpertact.getCreateBy())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只能删除自己创建的数据！");
            }
            if (Objects.nonNull(wQbdTeamExpertact.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_TEMP_TOBEREPORTED.equals(wQbdTeamExpertact.getReportStatus()) && !ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED.equals(wQbdTeamExpertact.getReportStatus())) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，只允许删除待上报和待报集团的数据");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        int result = wQbdTeamExpertactService.delByIdArray(id.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
     * 功能描述: 跳转到导入页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description = "跳转到专家活动导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdTeamExpertact/import";
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @param request
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到专家活动导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdTeamExpertact.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
     * 功能描述: 导出专家活动数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-07-03 08:42:32
     */
    @RequestMapping("/exportData")
    @Action(description = "导出专家活动数据信息", detail = "导出专家活动数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        List<WQbdTeamExpertact> wQbdTeamExpertacts = this.wQbdTeamExpertactService.queryAll(queryFilter);
        if (wQbdTeamExpertacts.isEmpty()) {
            wQbdTeamExpertacts.add(new WQbdTeamExpertact());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wQbdTeamExpertacts, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
     * 导入资源文件
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/importData")
    @ResponseBody
    public ResultData importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        MultipartFile multipartFile = request.getFile("file");
        TableEntity excelEntity = new CustomExcelReader().readFile(multipartFile.getInputStream());
        Map<String, Object> map = new AbstractImpUtil() {
            @Override
            public ReturnType customValidation(String fieldName, String fieldValue) {
                ReturnType returnType = null;
                if ("expert".equals(fieldName)) {
                    QueryFilter queryFilter = new QueryFilter(request);
                    queryFilter.clear();
                    queryFilter.addFilter("name", fieldValue);
                    List<WQbdTeamExpertgroup> wQbdTeamExpertgroups = wQbdTeamExpertgroupService.queryList(queryFilter);
                    if (null == wQbdTeamExpertgroups || wQbdTeamExpertgroups.size() == 0) {
                        returnType = new ReturnType();
                        returnType.setMsg("不存在此专家");
                    }
                }
                return returnType;
            }
        }.reverseModels(excelEntity, WQbdTeamExpertact.class);
        String msg = map.get("msg").toString();
        List<WQbdTeamExpertact> list = (List<WQbdTeamExpertact>) map.get("instList");
        if (StringUtil.isEmpty(msg)) {
            this.wQbdTeamExpertactService.addImportData(list);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("dataSource.importXml.success");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail(msg);
        }
    }

    /**
     * 查询上报的信息
     *
     * @param id        业务数据主键
     * @param tableName 业务表名
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(@RequestParam("id") String id, @RequestParam("tableName") String tableName) throws IllegalAccessException {
        //业务数据
        List<WQbdTeamExpertact> reportList = wQbdTeamExpertactService.reportList(id, tableName);
        ZhiLiangConst.showName(reportList);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }

}
